<?php
namespace Api\Event;

/**
 * APP首页栏目
 * @author liubo <liubo@ilongyuan.com.cn>
 */
class AppTopicEvent extends BaseEvent
{
    public function _initialize()
    {
        parent::_initialize();
        $this->service = service('AppTopic');
    }

    public function lists()
    {
        /*
        templete
        [
            video:1
            news:1
            race:1
        ]
         */
        $list = $this->service->where(['status' => 1])
                              ->order('sort asc')
                              ->field('id,title,code,href,template')
                              ->select();
        if (empty($list)) {
            return [];
        }
        foreach ($list as &$value) {
            $template = json_decode($value['template'], true);
            $value['template'] = $template ?: [];
        }
        return array_values($list);
    }

    public function getUserTopics($uid)
    {
        $all = array_column($this->lists(), null, 'id');
        $map = [
            'uid' => $uid,
            'topic_id'  => ['$in' => array_keys($all)]
        ];
        //用户关注的栏目
        $res = service('UserAppTopic')->where($map)->getField('topic_id', true);

        //如果没有关注，返回全部栏目
        if (empty($res)) {
            return array_values($all);
        }

        $list = [];
        foreach ($res as $id) {
            $list[] = $all[$id];
        }
        return $list;
    }

    public function setUserTopics($uid, $ids = [])
    {
        service('UserAppTopic')->where(['uid' => $uid])->delete();
        foreach ($ids as $id) {
            service('UserAppTopic')->add(['uid' => $uid, 'topic_id' => $id]);
        }
        return true;
    }
}